﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace NSATBPortal
{
    public partial class OpenEvidence : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string sFilename = Server.UrlDecode(Request.QueryString["Filename"].ToString());
                string sVal = Request.QueryString["ID"].ToString();
                int iResTestEvidenceID = int.Parse(sVal);

                using (ATBSchemaDB objATBDB = new ATBSchemaDB())
                {

                    SqlCommand cmd = objATBDB.GetEvidenceBinaryData(iResTestEvidenceID);
                    // sequential access is used for raw access
                    using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
                    {
                        if (reader.Read())
                        {
                            // must be lower than 85K (to avoid Large Object Heap fragmentation)
                            byte[] chunk = new byte[0x10000];
                            long read;
                            long offset = 0;
                            do
                            {
                                read = reader.GetBytes(0, offset, chunk, 0, chunk.Length);
                                if (read > 0)
                                {
                                    Response.OutputStream.Write(chunk, 0, (int)read);
                                    offset += read;
                                }
                            }
                            while (read > 0);
                            Response.AddHeader("Content-Type", "application/octet-stream");
                            Response.AddHeader("Content-Disposition", "inline; filename=" + sFilename);
                        }
                    }

                }
            }

        }
    }
}